package chap_05;

import chap_04.Dish;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

/**
 * 数值流
 */
public class Run_06 {
    List<Dish> menu = Arrays.asList(
            new Dish("pork", false, 800, Dish.Type.MEAT),
            new Dish("beef", false, 700, Dish.Type.MEAT),
            new Dish("chicken", false, 400, Dish.Type.MEAT),
            new Dish("french fries", true, 530, Dish.Type.OTHER),
            new Dish("rice", true, 350, Dish.Type.OTHER),
            new Dish("season fruit", true, 120, Dish.Type.OTHER),
            new Dish("pizza", true, 550, Dish.Type.OTHER),
            new Dish("prawns", false, 300, Dish.Type.FISH),
            new Dish("salmon", false, 450, Dish.Type.FISH) );

    /**
     * 映射到数值流
     */
    @Test
    public void demo_01() {
        int sum = menu.stream()
                .mapToInt(m -> m.getCalories())
                .sum();
        System.out.println(sum);
    }

    /**
     * 转换回对象流
     */
    @Test
    public void demo_02() {
        IntStream intStream = menu.stream().mapToInt(Dish::getCalories);
        Stream<Integer> boxed = intStream.boxed();
        boxed.collect(toList()).forEach(System.out::println);
    }

    /**
     * 勾股数
     */
    @Test
    public void demo_03() {
        Stream<Integer> range = IntStream.rangeClosed(1, 100).boxed();

        Stream<int[]> stream = range
                .flatMap(a ->
                        IntStream.rangeClosed(a, 100)
                                .filter(b -> Math.sqrt(a * a + b * b) % 1 == 0)
                                .mapToObj(b ->
                                        new int[]{a, b, (int) Math.sqrt(a * a + b * b)}));

        stream.collect(toList()).forEach(a -> {
            Arrays.stream(a).forEach(item -> System.out.print(item + " "));
            System.out.println();
        });
    }
}
